package com.czk.doc;

import com.czk.util.ClientUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * 聚合查询
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/14 18:09
 */
public class AggregationQuery {
    public static void main(String[] args) throws IOException {
        // 客户端
        RestHighLevelClient highLevelClient = ClientUtil.getHighLevelClient();
        // 构建请求
        SearchRequest searchRequest = new SearchRequest();
        // builder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 最大值
        MaxAggregationBuilder age = AggregationBuilders.max("age").field("age");
        // 设置进入search
        searchSourceBuilder.aggregation(age);
        // 设置
        searchRequest.indices("user").source(searchSourceBuilder);
        // 查询
        SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit.getSourceAsString());
        }
        highLevelClient.close();
    }
}
